﻿using RestSharp;
using RuYiAdmin.Net.Common.Global;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace RuYiAdmin.Net.Common.Utility
{
    /// <summary>
    /// RestSharp工具类
    /// </summary>
    public class RestSharpUtil
    {
        /// <summary>
        /// 发送请求
        /// </summary>
        /// <param name="baseUrl">请求地址</param>
        /// <param name="resource">请求方法</param>
        /// <param name="method">请求类型</param>
        /// <param name="parameters">参数</param>
        /// <param name="keyValuePairs">头部参数</param>
        /// <returns>RestResponse</returns>
        public static async Task<RestResponse> SendRequest(string baseUrl, string resource, Method method,
            List<Parameter> parameters, Dictionary<String, String> keyValuePairs = null)
        {
            RestClient client = new RestClient(baseUrl);

            RestRequest request = new RestRequest(resource, method);
            request.Timeout = GlobalContext.RestSharpConfig.TimeOut;

            request.AddHeader("Content-Type", "application/json;charset=utf-8");
            foreach (var item in keyValuePairs)
            {
                request.AddOrUpdateHeader(item.Key, item.Value);
            }

            foreach (Parameter item in parameters)
            {
                request.AddParameter(item);
            }

            RestResponse response = await (Task<RestResponse>)client.ExecuteAsync(request);

            return response;
        }
    }
}
